﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evoucher.Business.Models;
using Mani.Common;

public partial class admin_vouchers_VoucherType_AddEdit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) {
            LoadProviders();

            if ( !String.IsNullOrEmpty(Request.QueryString["id"]) )
                LoadVoucherTypes();
        }
    }

    private void LoadProviders()
    {
        IVoucherRepository repo = new VoucherRepository();
        List<Provider> providers = repo.GetProviders();
        ddlProvider.DataSource = providers;
        ddlProvider.DataValueField = "Id";
        ddlProvider.DataTextField = "Name";
        ddlProvider.DataBind();
    }

    private void LoadVoucherTypes()
    {
        int id = Convert.ToInt32( Request.QueryString["id"] );
        IVoucherRepository repo = new VoucherRepository();
        VoucherType vt = repo.GetVoucherTypeById(id);
        txtVoucherTypeDesc.Text = vt.Description;
        txtFormat.Text = vt.Format;
        txtPrice.Text = vt.Price.ToString();
        vt.ProviderReference.Load();
        ddlProvider.Items.FindByValue(vt.Provider.Id.ToString()).Selected = true;
        cbActive.Checked = vt.Active;
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(Request.QueryString["id"]))
            NewVoucherType();
        else
            SaveChanges();

        UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شد");
        UIHelper.ClientRedirect(this, "VoucherTypes.aspx");
    }

    private void SaveChanges()
    {
        int id = Convert.ToInt32(Request.QueryString["id"]);
        IVoucherRepository repo = new VoucherRepository();
        VoucherType vt = repo.GetVoucherTypeById(id);

        vt.Active = cbActive.Checked;
        vt.Description = txtVoucherTypeDesc.Text;
        vt.Price = Convert.ToInt64(txtPrice.Text);
        vt.Format = txtFormat.Text;

        repo.persist();
    }

    private void NewVoucherType()
    {
        IVoucherRepository repo = new VoucherRepository();
        VoucherType vt = new VoucherType();
        vt.Active = cbActive.Checked;
        vt.Description = txtVoucherTypeDesc.Text;
        vt.Price = Convert.ToInt64(txtPrice.Text);
        vt.Provider = repo.GetProviderById(Convert.ToInt32(ddlProvider.SelectedValue));
        vt.Format = txtFormat.Text;

        repo.AddToVoucherTypes(vt);
        repo.persist();
    }
}